import { useUserStore } from '@/common/stores'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      // login
      path: '/login',
      component: () => import('@/views/login/index.vue'),
    },
    {
      path: '/',
      component: () => import('@/views/layout/index.vue'),
      redirect: '/home',
      children: [
        {
          // 首页
          path: '/home',
          component: () => import('@/views/home/index.vue'),
        },

        {
          // 推荐页
          path: '/recommend',
          component: () => import('@/views/recommend/index.vue'),
        },
        {
          // 技术文章
          path: '/technicalarticles',
          component: () => import('@/views/technicalarticles/index.vue'),
        },
        {
          // 聊天室
          path: '/chatroom',
          component: () => import('@/views/chatroom/index.vue'),
        },
        {
          // Coder社区
          path: '/codercommunity',
          component: () => import('@/views/codercommunity/index.vue'),
        },
        {
          // notice通知
          path: '/notice',
          component: () => import('@/views/notice/index.vue'),
        },
        // 课程
        {
          path: '/course/:id',
          component: () => import('@/views/course/index.vue'),
        },
        // 课程视频播放页
        {
          path: '/course/:id/video',
          component: () => import('@/views/course/video/index.vue'),
        },
        {
          // 我的
          path: '/my',
          component: () => import('@/views/my/index.vue'),
          props: route => ({ tab: route.query.tab }),  // 将查询参数作为 prop 传递给组件
        },
        {
          // 发布文章 草稿
          path: '/drafts',
          component: () => import('@/views/drafts/index.vue'),
        },
        {
          // 文章详情页
          path: '/articledetails/:id',
          component: () => import('@/views/articledetails/index.vue'),
        },
        {
          // 讲师详情
          path: '/lecturerdetails',
          component: () => import('@/views/lecturerdetails/index.vue'),
        },
        {
          // 搜索页
          path: '/search',
          component: () => import('@/views/search/index.vue'),
        },
        {
          // 搜索详情页
          path: '/search-details',
          component: () => import('@/views/searchdetails/index.vue'),
        },
      ],
    },
  ],
})

// 登录访问拦截
router.beforeEach(to => {
  const useStore = useUserStore()
  // 测试 某些模块需要登录才能访问
  const interceptedPaths = ['/drafts']
  if (
    interceptedPaths.includes(to.path) &&
    !useStore.userInfo &&
    to.path !== '/login'
  ) {
    // 将用户重定向到登录页面
    return '/login'
  }
})

export default router
